package com.silence.gankio.adapter

import android.graphics.Bitmap
import android.util.ArrayMap
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.silence.gankio.R
import com.silence.gankio.bean.GankIoData

class GankWealAdapter(data: MutableList<GankIoData>?) :
    BaseQuickAdapter<GankIoData, BaseViewHolder>(R.layout.item_gank_weal, data) {

    override fun convert(helper: BaseViewHolder, item: GankIoData) {

        val ivPhoto = helper.getView<ImageView>(R.id.item_iv_photo)

        if ((0 != (item.width or item.height)) and (0F != item.rate)) {
            val params = helper.itemView.layoutParams
            params.height = (ivPhoto.measuredWidth / item.rate).toInt()
            helper.itemView.layoutParams = params
        }

        helper.setText(R.id.item_tv_title, item.desc)

        ivPhoto.setImageBitmap(null)

        Glide.with(mContext)
            .load(item.url)
            .asBitmap()
            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
            .into(object : SimpleTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
                    resource?.let { bitmap ->
                        if ((0 != (item.width or item.height)) and (0F != item.rate)) {
                            ivPhoto.setImageBitmap(bitmap)
                        } else{
                            val width = bitmap.width
                            val height = bitmap.height
                            val rate: Float = width.toFloat() / height.toFloat()

                            item.width = width
                            item.height = height
                            item.rate = rate

                            val params = helper.itemView.layoutParams
                            params.height = (ivPhoto.measuredWidth / rate).toInt()
                            helper.itemView.layoutParams = params
                            ivPhoto.setImageBitmap(bitmap)
                        }
                    }
                }
            })

    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }
}